package com.atguigu.servicebase.exceptionhandler;

import com.atguigu.commonutils.ExceptionUtil;
import com.atguigu.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j //将错误日志输出到文件步骤一
public class GlobalExceptionHandler {

    //全局异常
    @ExceptionHandler(Exception.class)//Exception.class指所有异常
    @ResponseBody //为了返回数据
    public R error(Exception e) {
        e.printStackTrace();
        return R.error().message("执行了全局异常处理..");
    }

    //特定异常
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public R error(ArithmeticException ae){
        ae.printStackTrace();
        return R.error().message("数学算术异常");
    }

    //自定义异常 系统不会自动抛出自定义的异常
    @ExceptionHandler(WdException.class)
    @ResponseBody
    public R error(WdException e){
        log.error(e.getMessage());//将错误日志输出到文件步骤二
        log.error(ExceptionUtil.getMessage(e));
        e.printStackTrace();
        return R.error().message(e.getMsg()).code(e.getCode());
    }
}
